let pagenum = 1;
let pagesize = 2;
function fn(pam) {
  $.ajax({
    url: "/admin/users",
    data: pam,
    success: function (res) {
      let str = "";
      res.data.forEach((item) => {
        str += `<tr>
        <td>${item.id}</td>
        <td>${item.username}</td>
        <td>${item.nickname}</td>
        <td>${item.email}</td>
        <td>
          <button
            data-id="${item.id}"
            type="button"
            class="layui-btn layui-btn-xs "
          >
            <a
              style="color: #fff"
              target="fn"
              href="./edit.html?id=${item.id}"
              >编辑</a
            >
          </button>
          <button
            data-id="${item.id}"
            type="button"
            class="layui-btn layui-btn-xs layui-btn-danger delete"
          >
            删除
          </button>
          <button
            data-id="${item.id}"
            type="button"
            class="layui-btn layui-btn-xs layui-btn-normal delete"
          >
            重置密码
          </button>
        </td>
      </tr>`;
        $("tbody").html(str);
        fenye(res.total);
      });
    },
  });
}
fn({
  pagenum: pagenum,
  pagesize: pagesize,
});

// 分页
function fenye(a) {
  let laypage = layui.laypage;
  laypage.render({
    elem: "page", //这里的testl 是id 不用加#
    count: a, //数据总数
    limit: pagesize,
    limits: [2, 3, 5, 10],
    curr: pagenum,
    layout: ["limit", "prev", "page", "next", "count", "skip"],
    jump: function (obj, first) {
      //obj包含了当前分页的所有参数，比如：
      pagenum = obj.curr;
      pagesize = obj.limit;
      //首次不执行
      if (!first) {
        fn({
          pagenum: pagenum,
          pagesize: pagesize,
        });
      }
    },
  });
}

// 删除用户
$("tbody").on("click", 'button:contains("删除")', function () {
  let id = $(this).data("id");
  layer.confirm("确定删除吗？", function (index) {
    $.ajax({
      type: "DELETE",
      url: "/admin/users/" + id,
      success: function (res) {
        if (res.status === 0) {
          layer.msg(res.message);
          fn();
        }
      },
    });
    layer.close(index);
  });
});

//重置密码
$("tbody").on("click", 'button:contains("重置密码")', function () {
  let id = $(this).data("id");
  let index = layer.open({
    type: 1,
    title: "重置密码",
    content: $("#repwd-form-tpl").html(),
    area: ["500px", "250px"],
  });
  // 重置密码
  $("#repwd-form").on("submit", function (e) {
    e.preventDefault();
    $.ajax({
      type: "PUT",
      data: {
        password: $("#repwd-form input[name=password]").val(),
      },
      url: "/admin/users/" + id,
      success: function (res) {
        layer.msg(res.message);
        layer.close(index);
      },
    });
  });
});
